package sf.actions;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.JOptionPane;
import javax.swing.KeyStroke;

import sf.model.SQLTableModel;
import sf.view.StandardForm;

public class ActionBrisanje extends SFAbstractAction {

	private static final long serialVersionUID = 1L;

	private StandardForm parentForm;

	ActionBrisanje(StandardForm parentForm) {
		this.parentForm = parentForm;
		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_B,
				ActionEvent.CTRL_MASK));
		putValue(MNEMONIC_KEY, KeyEvent.VK_B);
		putValue(SMALL_ICON, loadIcon("img/brisanje.png"));
		putValue(NAME, "Brisanje");
		putValue(SHORT_DESCRIPTION, "Brisanje");
	}

	public void actionPerformed(ActionEvent e) {
		int row = parentForm.getBrowser().getSelectedRow();
		if (row != -1) {
			Object[] options = { "Da", "Ne" };
			int n = JOptionPane.showOptionDialog(parentForm,
					"Da li ste sigurni da zelite da obrisete ?", "Brisanje",
					JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
					null, options, options[1]);

			if (n == 0)
				removeRow(row);
		}
	}

	private void removeRow(int index) {
		SQLTableModel tableModel = (SQLTableModel) parentForm.getBrowser()
				.getTable().getModel();

		if (!tableModel.deleteRow(parentForm.getDetailsPane().getFieldsAndValues(), index))
			JOptionPane.showMessageDialog(parentForm, "<html><b>Brisanje neuspesno.</b></html>", "Greska", JOptionPane.ERROR_MESSAGE);
		else {
			int newIndex = index;
			if (index == tableModel.getRowCount() - 1)
				newIndex--;
			if (tableModel.getRowCount() > 0)
				parentForm.getBrowser().setSelectedRow(newIndex);
		}
	}

	public void setButtonMode(int mode) {
		if ((mode & StandardForm.MODE_EDIT) != 0)
			this.setEnabled(true);
		else
			this.setEnabled(false);
	}
}
